#!/usr/bin/python
# -*- encoding: utf8 -*-

import os
import sys

_default_dict_script = 'link_dict.py'

def get_dict(filename=_default_dict_script):
    # make sure link_dict.py is reexecuted. reload(module) doesn't work
    global_dict = {}
    if not os.path.exists(_default_dict_script):
        print >>sys.stderr, "INFO: The link dictionary %s doesn't exist. Create an empty one."
        save_dict({})

    execfile(filename, global_dict)
    return global_dict['link_dict']

def save_dict(adict, filename=_default_dict_script):
    def get_header():
        return ['#!/usr/bin/python\n',
                '# -*- encoding: utf8 -*-\n\n']

    def get_dict_repr():
        lines = ['link_dict = {\n']
        for key, value in sorted(adict.items()):
            key, value = escaped(key, value)
            msg = "    u'%s': u'%s',\n" % (key, value)
            lines.append(msg.encode('utf8'))
        lines.append('}\n')
        return lines

    lines = get_header()
    lines += get_dict_repr()

    fw = open(filename, "w")
    fw.write("".join(lines))
    fw.close()

def escaped(*names):
    return [name.replace("'", "\\'") for name in names]
